package com.frogs.ucenter.util.sms;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.jsoup.Connection.Method;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.entity.SmsMessageMqEntity;

@Component
public class PartnerSmsQxHelper {

	private static Logger log = LoggerFactory.getLogger(PartnerSmsQxHelper.class);
	private String sendUrl;
	private String operID;
	private String operPass;
	private String appendID;

	public void setSendUrl(String sendUrl) {
		this.sendUrl = sendUrl;
	}

	public void setOperID(String operID) {
		this.operID = operID;
	}

	public void setOperPass(String operPass) {
		this.operPass = operPass;
	}

	public void setAppendID(String appendID) {
		this.appendID = appendID;
	}

	public String getSendUrl() {
		return this.sendUrl;
	}
	
	public String sendSms(SmsMessageMqEntity smsMessageMqEntity) {
		/**
		 * 用于把消息发送到短信平台
		 */
		/*
		 * http://221.179.180.158:9007/QxtSms/QxtFirewall?OperID=test&OperPass=test
		 * &
		 * SendTime=&ValidTime=&AppendID=1234&DesMobile=13900000000&Content=%D6%
		 * D0%CE%C4%B6%CC%D0%C5abc&ContentType=8
		 */
		String result = "";
		String Content = "";
		try {
			Content = URLEncoder.encode(smsMessageMqEntity.getContent(),"GBK");;
		} catch (UnsupportedEncodingException e1) {
			log.error("func[sendSms] content["+smsMessageMqEntity.getContent()+"] exception[" + e1.getStackTrace() + "]");
			return "";
		}
		String[] params = { "OperID", this.operID, "OperPass", this.operPass,
				"AppendID", this.appendID, "SendTime", "", "ValidTime", "",
				"Content", Content, "ContentType", "8" };
		String srl=this.sendUrl+"?";
		for (int i = 0; i < params.length; i += 2) {
            String key = params[i];
            String value = params[i+1];
            srl=srl+key+"="+value+"&";
        }
		String[] param = {"DesMobile", smsMessageMqEntity.getReceiver()};
		srl=srl.substring(0, srl.length()-1);
		try {
			
			result = Jsoup
					.connect(srl)
					.timeout(6000)
					.header("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0;)")
					.header("Accept",
							"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*")
					.method(Method.GET).ignoreContentType(true).data(param)
					.execute().body();
			//result="<code>03</code>";
		} catch (Exception e) {
			log.error("func[sendSms] request[" + srl + "] error[" + e.getMessage() + "]", e);
			throw new ServiceOperationException("发送到短信通信平台方失败：" + e.getMessage());
		}
		
		return result;
	} 
}
